package link.chengguo.orangemall.shms.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import link.chengguo.orangemall.annotation.SysLog;
import link.chengguo.orangemall.enums.AllEnum;
import link.chengguo.orangemall.oms.entity.OmsCartItem;
import link.chengguo.orangemall.oms.entity.OmsOrder;
import link.chengguo.orangemall.oms.service.IOmsCartItemService;
import link.chengguo.orangemall.oms.service.IOmsOrderService;
import link.chengguo.orangemall.pms.entity.PmsProduct;
import link.chengguo.orangemall.pms.service.IPmsProductService;
import link.chengguo.orangemall.shms.entity.ShmsShopAccount;
import link.chengguo.orangemall.shms.entity.ShmsShopCategory;
import link.chengguo.orangemall.shms.entity.ShmsShopInfo;
import link.chengguo.orangemall.shms.service.IShmsShopAccountService;
import link.chengguo.orangemall.shms.service.IShmsShopCategoryService;
import link.chengguo.orangemall.shms.service.IShmsShopInfoService;
import link.chengguo.orangemall.sys.entity.SysArea;
import link.chengguo.orangemall.sys.entity.SysOrderType;
import link.chengguo.orangemall.sys.entity.SysUser;
import link.chengguo.orangemall.sys.service.ISysAreaService;
import link.chengguo.orangemall.sys.service.ISysOrderTypeService;
import link.chengguo.orangemall.sys.service.ISysUserService;
import link.chengguo.orangemall.util.EasyPoiUtils;
import link.chengguo.orangemall.util.LoginThirdUtils;
import link.chengguo.orangemall.util.UserUtils;
import link.chengguo.orangemall.utils.CommonResult;
import link.chengguo.orangemall.utils.ValidatorUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @author yzb
 * @date 2019-12-18
 * 店铺信息
 */
@Slf4j
@RestController
@Api(tags = "ShmsShopInfoController ", description = "店铺信息")
@RequestMapping("/shms/shmsShopInfo")
public class ShmsShopInfoController {

    @Resource
    private IShmsShopInfoService IShmsShopInfoService;
    @Autowired
    private IPmsProductService pmsProductService;
    @Autowired
    private IOmsOrderService omsOrderService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IShmsShopAccountService shmsShopAccountService;
    @Autowired
    private IOmsCartItemService omsCartItemService;
    @Autowired
    private IShmsShopCategoryService categoryService;
    @Autowired
    private ISysAreaService areaService;

    @SysLog(MODULE = "shms", REMARK = "根据条件查询所有店铺信息列表")
    @ApiOperation("根据条件查询所有店铺信息列表")
    @GetMapping(value = "/list2")
    @PreAuthorize("hasAuthority('shms:shmsShopInfo:read')")
    public Object getShmsShopInfoByPage(ShmsShopInfo entity,
                                        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
//            SysUser user= UserUtils.getCurrentMember();
//            entity.setCityCode(user.getCityCode());//查询同一个区域下的用户
            IPage<ShmsShopInfo> list = IShmsShopInfoService.page(new Page<ShmsShopInfo>(pageNum, pageSize), new QueryWrapper<>(entity).orderByDesc("id"));
            list.getRecords().forEach(shop -> {
                if (shop.getCategoryId() != null) {
                    ShmsShopCategory category = categoryService.getById(shop.getCategoryId());
                    if (category.getName() != null) {
                        shop.setCategoryName(category.getName());
                    }
                }
            });
            return new CommonResult().success(list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据条件查询所有店铺信息列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "shms", REMARK = "根据条件查询所有店铺信息列表")
    @ApiOperation("根据条件查询所有店铺信息列表")
    @GetMapping(value = "/list")
    @PreAuthorize("hasAuthority('shms:shmsShopInfo:read')")
    public Object getShmsShopInfoByPage2(ShmsShopInfo entity,
                                         @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                         @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {

            if (UserUtils.getCurrentMember().getPlatform().equals(AllEnum.PlatformType.Tenant.code())) {
                IPage<ShmsShopInfo> page = IShmsShopInfoService.customPageList(pageNum, pageSize, entity);
                page.getRecords().forEach(shop -> {
                    if (shop.getCategoryId() != null) {
                        ShmsShopCategory category = categoryService.getById(shop.getCategoryId());
                        if (category != null && category.getName() != null) {
                            shop.setCategoryName(category.getName());
                        }
                    }
                });
                return new CommonResult().success(page);
            } else if (UserUtils.getCurrentMember().getPlatform().equals(AllEnum.PlatformType.Agent.code())) {
                SysUser user = UserUtils.getCurrentMember();
                entity.setCityCode(user.getCityCode());
                Page<ShmsShopInfo> list = IShmsShopInfoService.customPageList(pageNum, pageSize, entity);
                list.getRecords().forEach(shop -> {
                    if (shop.getCategoryId() != null) {
                        ShmsShopCategory category = categoryService.getById(shop.getCategoryId());
                        if (category != null && category.getName() != null) {
                            shop.setCategoryName(category.getName());
                        }
                    }
                });
//          IPage<ShmsShopInfo> list= IShmsShopInfoService.page(new Page<ShmsShopInfo>(pageNum, pageSize), new QueryWrapper<>(entity).orderByDesc("id"));
                return new CommonResult().success(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据条件查询所有店铺信息列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "shms", REMARK = "保存店铺信息")
    @ApiOperation("保存店铺信息")
    @PostMapping(value = "/create")
    @PreAuthorize("hasAuthority('shms:shmsShopInfo:create')")
    public Object saveShmsShopInfo( ShmsShopInfo entity) {
        try {
//            if (UserUtils.getCurrentMember().getPlatform().equals(AllEnum.PlatformType.Tenant.code())){
//                if (IShmsShopInfoService.createShopInfo(entity)) {
//                    return new CommonResult().success();
//                }
//            }else if(UserUtils.getCurrentMember().getPlatform().equals(AllEnum.PlatformType.Agent.code())){
//                entity.setCityCode(UserUtils.getCurrentMember().getCityCode());
//                entity.setCreateTime(new Date());
//                if (IShmsShopInfoService.createShopInfo(entity)) {
//                    return new CommonResult().success();
//                }
//            }
            if (IShmsShopInfoService.createShopInfo(entity)) {
                IShmsShopInfoService.saveSmsAndSendCode(entity);
                return new CommonResult().success();
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("保存店铺信息：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }


    @SysLog(MODULE = "sys", REMARK = "商家登录密码重置")
    @ApiOperation("商家登录密码重置")
    @PostMapping(value = "/resetShopPwd")
    public Object resetPwd(@RequestParam("id") Long id) {
        try {
            SysUser user = UserUtils.getCurrentMember();
            if (IShmsShopInfoService.resetShopPwd(id)) {
                return new CommonResult().success();
            } else {
                return new CommonResult().failed("密码重置失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("密码重置：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
    }


    @SysLog(MODULE = "shms", REMARK = "更新店铺信息")
    @ApiOperation("更新店铺信息")
    @PostMapping(value = "/update/{id}")
    @PreAuthorize("hasAuthority('shms:shmsShopInfo:update')")
    public Object updateShmsShopInfo(@RequestBody ShmsShopInfo entity) {
        try {
            entity.setUpdateTime(new Date());
            if (IShmsShopInfoService.updateById(entity)) {
                List<PmsProduct> list = pmsProductService.list(new QueryWrapper<PmsProduct>().eq("shop_id", entity.getId()));
                if (list.size() > 0) {
                    for (PmsProduct pmsProduct : list) {
                        pmsProduct.setShopName(entity.getName());
                        pmsProduct.setCityCode(entity.getCityCode());
                        pmsProductService.updateById(pmsProduct);
                    }
                }
                SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("shop_id", entity.getId()));

                sysUser.setCityCode(entity.getCityCode());
                sysUserService.updateById(sysUser);

                ShmsShopAccount shmsShopAccount = shmsShopAccountService.getOne(new QueryWrapper<ShmsShopAccount>().eq("shop_id", entity.getId()));
                shmsShopAccount.setCityCode(entity.getCityCode());
                shmsShopAccountService.updateById(shmsShopAccount);
                List<OmsOrder> list2 = omsOrderService.list(new QueryWrapper<OmsOrder>().eq("shop_id", entity.getId()));
                if (list2.size() > 0) {
                    for (OmsOrder omsOrder : list2) {
                        omsOrder.setShopName(entity.getName());
                        omsOrder.setCityCode(entity.getCityCode());
                        omsOrderService.updateById(omsOrder);
                    }
                }
                List<OmsCartItem> list3 = omsCartItemService.list(new QueryWrapper<OmsCartItem>().eq("shop_id", entity.getId()));
                if (list3.size() > 0) {
                    for (OmsCartItem omsCartItem : list3) {
                        omsCartItem.setShopName(entity.getName());
                        omsCartItem.setCityCode(entity.getCityCode());
                        omsCartItemService.updateById(omsCartItem);
                    }
                }
                return new CommonResult().success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新店铺信息：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "shms", REMARK = "入驻店铺审核")
    @ApiOperation("入驻店铺审核")
    @PostMapping(value = "/shopVerify")
    public Object shopVerify(@RequestBody ShmsShopInfo entity) {
        try {
            entity.setUpdateTime(new Date());
            if (IShmsShopInfoService.shopVerify(entity)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("入驻店铺审核：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "shms", REMARK = "删除店铺信息")
    @ApiOperation("删除店铺信息")
    @GetMapping(value = "/delete/{id}")
    @PreAuthorize("hasAuthority('shms:shmsShopInfo:delete')")
    public Object deleteShmsShopInfo(@ApiParam("店铺信息id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("店铺信息id");
            }
            if (IShmsShopInfoService.removeById(id)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除店铺信息：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "shms", REMARK = "给店铺信息分配店铺信息")
    @ApiOperation("查询店铺信息明细")
    @GetMapping(value = "/{id}")
    @PreAuthorize("hasAuthority('shms:shmsShopInfo:read')")
    public Object getShmsShopInfoById(@ApiParam("店铺信息id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("店铺信息id");
            }
            ShmsShopInfo entity = IShmsShopInfoService.getById(id);
            if (entity.getCategoryId() != null) {
                ShmsShopCategory category = categoryService.getById(entity.getCategoryId());
                SysArea areap = areaService.getById(entity.getProvince());
                SysArea areac = areaService.getById(entity.getCity());
                SysArea aread = areaService.getById(entity.getDistrict());
                if (category != null && category.getName() != null) {
                    entity.setCategoryName(category.getName());
                }
                if (areap != null && areap.getExtName() != null) {
                    entity.setProvinceName(areap.getExtName());
                }
                if (areac != null && areac.getExtName() != null) {
                    entity.setCityName(areac.getExtName());
                }
                if (aread != null && aread.getExtName() != null) {
                    entity.setDistrictName(aread.getExtName());
                }
            }
            return new CommonResult().success(entity);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询店铺信息明细：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }

    }

    @ApiOperation(value = "批量删除店铺信息")
    @RequestMapping(value = "/delete/batch", method = RequestMethod.GET)
    @SysLog(MODULE = "shms", REMARK = "批量删除店铺信息")
    @PreAuthorize("hasAuthority('shms:shmsShopInfo:delete')")
    public Object deleteBatch(@RequestParam("ids") List
            <Long> ids) {
        boolean count = IShmsShopInfoService.removeByIds(ids);
        if (count) {
            return new CommonResult().success(count);
        } else {
            return new CommonResult().failed();
        }
    }

    @SysLog(MODULE = "shms", REMARK = "登录商家账号")
    @ApiOperation("登录商家账号")
    @PreAuthorize("hasAuthority('sys:sysUser:loginByAgent')")
    @PostMapping(value = "/shopLogin")
    public Object shopLogin(@RequestBody ShmsShopInfo entity, HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
        String baseUrl = tempContextUrl.substring(0, tempContextUrl.length() - 6);
        CommonResult result = null;
        try {
            //组装请求参数
            JSONObject map = new JSONObject();
            map.put("username", entity.getContactMobile());
            map.put("password", entity.getPassword());
            String params = map.toString();
            result = LoginThirdUtils.loginByAgent(params, baseUrl);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新代理管理：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return result;
    }


    @SysLog(MODULE = "ams", REMARK = "验证是否有权限登录商家账号")
    @ApiOperation("验证是否有权限登录商家账号")
    @PreAuthorize("hasAuthority('sys:sysUser:loginByAdmin')")
    @PostMapping(value = "/hasAuthorityAgentLogin")
    public boolean hasAuthorityShopLogin() {
        return true;
    }

    @SysLog(MODULE = "shms", REMARK = "导出社区数据")
    @GetMapping("/exportExcel")
    public void export(HttpServletResponse response, ShmsShopInfo entity) {
        // 模拟从数据库获取需要导出的数据
        List<ShmsShopInfo> personList = IShmsShopInfoService.list(new QueryWrapper<>(entity).orderByDesc("id"));
        // 导出操作
        EasyPoiUtils.exportExcel(personList, "导出社区数据", "社区数据", ShmsShopInfo.class, "导出社区数据.xls", response);

    }

    @SysLog(MODULE = "shms", REMARK = "导入社区数据")
    @PostMapping("/importExcel")
    public void importUsers(@RequestParam MultipartFile file) {
        List<ShmsShopInfo> personList = EasyPoiUtils.importExcel(file, ShmsShopInfo.class);
        IShmsShopInfoService.saveBatch(personList);
    }
}


